package com.sinodata.common
{
	import com.sinodata.atmp.components.IconAlert;
	import com.sinodata.common.Application;
	
	import flash.events.Event;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.managers.CursorManager;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	
	import spark.collections.Sort;
	import spark.collections.SortField;

	public class DataService 
	{
		// Application.getInstance().service.exec()
		public function exec(method:String,param:Object,onResultHandler:Function,onFaultHandler:Function=null,showBusyCursor:Boolean=true,resultType:String="JSON"):void{
			var object:Object;
//			object.u = Application.getInstance().user_info.user_id;
			object = param;
			object.m = method;
			call_service(object,onResultHandler,onFaultHandler,showBusyCursor,resultType);
		}
		
		//访问服务器
		private function call_service(obj:Object,onResultHandler:Function,onFaultHandler:Function=null,showBusyCursor:Boolean=true,resultType:String="JSON"):void{			
			var service:HTTPService = new HTTPService();//创建HTTPService对象访问服务器
			service.url = Application.getInstance().serviceUrl + "?timestamp=" + new Date().time;
			service.useProxy = false;
			service.resultFormat = "e4x";
			service.method = "POST";
			service.addEventListener(ResultEvent.RESULT,onResultHandler);//访问服务器哦成功的监听事件
			if(onFaultHandler == null){
				service.addEventListener(FaultEvent.FAULT,onFault);//访问服务器失败的监听事件
			}else{
				service.addEventListener(FaultEvent.FAULT,onFaultHandler);//访问服务器失败的监听事件
			}
			if(showBusyCursor){
				service.addEventListener(Event.DEACTIVATE,onDeactive); //测试能否完成在请求后设置鼠标指针
				service.addEventListener(Event.ACTIVATE,onActivate);
			}
			obj.r = resultType;
			obj.t = new Date().time;
//			解析obj
			service.send(dataResolve(obj));
		}
		
		protected function onActivate(event:Event):void
		{
			//CursorManager.setBusyCursor();
		}
		
		protected function onDeactive(event:Event):void
		{
			CursorManager.removeBusyCursor();
		}
		
		private function onFault(event:FaultEvent):void{

			IconAlert.showError("网络链接异常");
		}
		
		//对sign属性进行整理
		private function dataResolve(obj:Object):Object{
			var array:Array = new Array();
			for(var sKey:String in obj){
				if(sKey == "image1" || sKey == "image2" ||sKey == "image3" ||sKey == "image4"){
					continue;
				}
				array.push(sKey);
			}
			array.sort();
			var s:String = "";
			for(var i:int = 0; i < array.length; i++){
				if(obj[array[i]] == null){
					continue;
				}
				s = s + array[i].toString().toLowerCase() + "=" + obj[array[i]] + "&";
			}
			//Alert.show("=====s====="+s + Application.getInstance().sign);
//			trace("=====s====="+s + Application.getInstance().sign);
			var md5:MD5 = new MD5();
			obj.s = md5.getMD5(s + Application.getInstance().sign);
			return obj;
		}
	}
}